<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */
namespace App\Controller\User;

use App\Controller\AppBaseController;
use App\Model\Act;
use App\Model\ActJoin;
use App\Model\ActVoteMedia;
use App\Model\ActVoteJoin;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\WxApiAuth;
use Hyperf\DbConnection\Db;

#[Controller(prefix: 'user')]
#[Middleware(WxApiAuth::class)]
class ActVoteController extends AppBaseController
{

    /**
     * 活动投票-作品列表
     * @param int $act_id
     * @return object
     * @throws \RedisException
     */
    #[RequestMapping(path: 'actVoteMediaList/{act_id}',methods: 'post,get')]
    public function actVoteMediaList(int $act_id): object
    {
        //redis锁名称，写在外面用户异常解锁
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            //活动信息
            $info = Act::where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            if($info->type != 6) return $this->reMsg->re(0,'活动类型有误');

            //获取本次活动的所有打卡点
            $list = ActVoteMedia::where('act_id',$act_id)->get();

            $vote_status = 0;
            //获取我的活动投票 记录
            $joinWhere['act_id'] = $act_id;
            $joinWhere['uid'] = $_user->id;
            $myActVote = ActVoteJoin::where($joinWhere)->first();
            if($myActVote && $myActVote->media_id){
                foreach ($list as $key=>$value) {
                    if(in_array($value->id,$myActVote->media_id)){
                        $value->is_vote = 1;
                        $vote_status = 1;
                    }else{
                        $value->is_vote = 0;
                    }
                }
            }else{
                foreach ($list as $key=>$value) {
                    $value->is_vote = 0;
                }
            }

            $backData = [
                'list'=>$list,
                'vote_status'=>$vote_status
            ];
            return $this->reMsg->re(1,'success',$backData);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 活动投票-作品投票
     * @param int $act_id
     * @return object
     * @throws \RedisException
     */
    #[RequestMapping(path: 'actVoteJoin/{act_id}',methods: 'post,get')]
    public function actVoteJoin(int $act_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            //查看打卡点是否存在
            $info = Act::with(['voteRule'])->where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //判断类型
            if($info->type != 6) return $this->reMsg->re(0,'活动类型有误');
            //判断开始时间
            if($info->start_time && time()<strtotime($info->start_time)) return $this->reMsg->re(0,'活动未开始');
            //判断结束时间
            if($info->end_time && time()>strtotime($info->end_time)) return $this->reMsg->re(0,'活动已结束');
            //判断参与人数
            if($info->max_limit>0 && $info->join_count>=$info->max_limit) return $this->reMsg->re(0,'参与人数超过限制');


            if(empty($info->voteRule) || !isset($info->voteRule->limit_num)) return $this->reMsg->re(0,'投票规则丢失');

            //获取投票作品id
            $media_id = $this->request->input('media_id',null);
//            $media_id = [1,2];
            if(empty($media_id) || !is_array($media_id)) return $this->reMsg->re(0,'提交信息有误');

            if(count($media_id)!=$info->voteRule->limit_num) return $this->reMsg->re(0,'必须选择'.$info->voteRule->limit_num.'个作品');

            //查看用户是否已经打开
            $searchWhere['act_id'] = $act_id;
            $searchWhere['uid'] = $_user->id;
            $voteMe = ActVoteJoin::where($searchWhere)->first();
            if($voteMe) return $this->reMsg->re(0,'本活动已投票');

            $insertData['party_id'] = $info->party_id;
            $insertData['act_id'] = $info->id;
            $insertData['uid'] = $_user->id;
            $insertData['media_id'] = $media_id;

            Db::beginTransaction();

            $insertRet = ActVoteJoin::create($insertData);
            if($insertRet){
                //增加投票数量
                ActVoteMedia::whereIn('id',$insertData['media_id'])->increment('vote_num');

                //需要往我们混动参加记录里面加一条 参与记录  不可重复
                $actWhere['act_id'] = $info->id;
                $actWhere['uid'] = $_user->id;
                $actJoinLog = ActJoin::where($actWhere)->first();
                if(empty($actJoinLog)){
                    $actWhere['party_id'] = $info->party_id;
                    $actWhere['title'] = $info->title;
                    $actWhere['photo'] = $info->photo;
                    ActJoin::create($actWhere);
                    Act::where('id',$info->id)->increment('join_count',1); //活动参与人数加1
                }
                Db::commit();
                return $this->reMsg->re(1,'success');
            }else{
                Db::rollBack();
                return $this->reMsg->re(0,'fail');
            }
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }

}